package cn.zh.stan.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.chiclam.android.updater.Updater;
import com.chiclam.android.updater.UpdaterConfig;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import cn.zh.stan.BaseUrl;
import cn.zh.stan.MyApplication;
import cn.zh.stan.R;
import cn.zh.stan.util.Loading;
import cn.zh.stan.util.ToastUtil;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class Login extends BaseActivity{

    TextView regist;
    EditText phone,pass;
    Button login;

    MyApplication mapp;

    SharedPreferences sp;

    ImageView pimag,wimg;

    LinearLayout phlin,pslin;

    TextView forget;

    SharedPreferences.Editor editor;

    private Dialog LDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mapp= (MyApplication) getApplication();
        sp=mapp.getSp();
        editor = sp.edit();
        boolean flag=sp.getBoolean("Flag",false);
        if (flag){
            Intent intent1=new Intent(Login.this,MainActivity.class);
            startActivity(intent1);
            finish();
           }
          regist();
          }


    public void regist(){
        regist= (TextView) findViewById(R.id.regist);
        phone= (EditText) findViewById(R.id.phone);
        pass= (EditText) findViewById(R.id.pass);
        login= (Button) findViewById(R.id.login);
        pimag= (ImageView) findViewById(R.id.pimag);
        phlin= (LinearLayout) findViewById(R.id.phlin);
        pslin= (LinearLayout) findViewById(R.id.pslin);
        forget= (TextView) findViewById(R.id.forget);

        wimg= (ImageView) findViewById(R.id.wimg);
        regist.setOnClickListener(this);
        login.setOnClickListener(this);
        pimag.setOnClickListener(this);
        wimg.setOnClickListener(this);
        forget.setOnClickListener(this);

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void afterTextChanged(Editable editable) {
             int leng=editable.length();
             if (leng>0){
                 pimag.setVisibility(View.VISIBLE);
                 phlin.setBackgroundResource(R.drawable.cprimbg);
             }else {
                 pimag.setVisibility(View.INVISIBLE);
                 phlin.setBackgroundResource(R.drawable.graybg);
             }
            }
        });

        pass.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void afterTextChanged(Editable editable) {
                int leng=editable.length();
                if (leng>0){
                    wimg.setVisibility(View.VISIBLE);
                    pslin.setBackgroundResource(R.drawable.cprimbg);
                }else {
                    wimg.setVisibility(View.INVISIBLE);
                    pslin.setBackgroundResource(R.drawable.graybg);
                }
               }
           });
         }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id=view.getId();
        switch (id){
            case R.id.regist:
                Intent intent=new Intent(Login.this,ReActivity.class);
                startActivity(intent);
                break;
            case R.id.login:
                LDialog= Loading.createLoadingDialog(this,"登录中...");
                getlogin();
                break;
            case R.id.pimag:
                phone.getText().clear();
                phlin.setBackgroundResource(R.drawable.graybg);
                pimag.setVisibility(View.INVISIBLE);
                break;
            case R.id.wimg:
                pass.getText().clear();
                pslin.setBackgroundResource(R.drawable.graybg);
                wimg.setVisibility(View.INVISIBLE);
                break;
            case R.id.forget:
                Intent intent1=new Intent(Login.this,ForgetPass.class);
                startActivity(intent1);
                break;
                }
             }




       public void getlogin(){
           final String username=phone.getText().toString();
           String userpass=pass.getText().toString();
           OkHttpUtils.post(BaseUrl.login)
                   .params("username",username)
                   .params("password",userpass)
                   .execute(new StringCallback() {
                       @Override
                       public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                           System.out.println("----------->登录=="+s);
                           try {
                               JSONObject js=new JSONObject(s);
                               Boolean State=js.getBoolean("State");
                               if (State){
                                  boolean Flag=js.getBoolean("Flag");
                                   Loading.closeDialog(LDialog);
                                  if (Flag){
                                      JSONObject Res=js.getJSONObject("Res");
                                      String Userid=Res.getString("UserId");
                                      editor.putString("uid",Userid);
                                      editor.putBoolean("Flag",Flag);
                                      editor.putString("phone",username);
                                      editor.commit();
                                      CloudPushService pushService = PushServiceFactory.getCloudPushService();
                                      pushService.bindAccount(username, new CommonCallback() {
                                          @Override
                                          public void onSuccess(String s) {
                                              System.out.println("-------->账号绑定成功=="+s);
                                            }
                                          @Override
                                          public void onFailed(String s, String s1) {
                                          }
                                      });
                                      Intent intent1=new Intent(Login.this,MainActivity.class);
                                      startActivity(intent1);
                                      finish();
                                  }else {
                                      String Msg=js.getString("Msg");
                                      ToastUtil.showShort(Login.this,Msg);
                                  }
                               }else {
                                   String Msg=js.getString("Msg");
                                   ToastUtil.showShort(Login.this,Msg);
                                }
                               Loading.closeDialog(LDialog);
                           } catch (JSONException e) {
                               e.printStackTrace();
                           }
                       }
                       @Override
                       public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                           super.onError(isFromCache, call, response, e);
                       }
                   });
               }




           //版本更新
    public void download(View view) {
        String url="http://releases.b0.upaiyun.com/hoolay.apk";
        UpdaterConfig config = new UpdaterConfig.Builder(this)
                .setTitle(getResources().getString(R.string.app_name))
                .setDescription(getString(R.string.system_download_description))
                .setFileUrl(url)
                .setCanMediaScanner(true)
                .build();
        Updater.get().showLog(true).download(config);
         }




    private boolean location(){
        if((ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            //  Dialog();
            // 你要申请的权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0145);
            return false;
             }
          return true;
           }


    //监听
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 0145:
                if(grantResults.length >0 &&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    //用户同意授权
                    Toast.makeText(this, "同意了", Toast.LENGTH_SHORT).show();


                }else{
                    //用户拒绝授权
                    //以下为跳转至手机设置界面
                    Toast.makeText(this, "拒绝了", Toast.LENGTH_SHORT).show();
//                    Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                    intent.setData(Uri.parse("package:" + getPackageName()));
//                    startActivity(intent);

                  }
                break;
               }
         }





    }
